package org.wm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.wm.constants.UserConstants;
import org.wm.entity.*;
import org.wm.exception.ServiceException;
import org.wm.mapper.SysRoleDeptMapper;
import org.wm.mapper.SysRoleMapper;
import org.wm.mapper.SysRoleMenuMapper;
import org.wm.mapper.SysUserRoleMapper;
import org.wm.service.ISysRoleService;
import org.wm.utils.SecurityUtils;
import org.wm.utils.ServiceUtils;
import org.wm.utils.SpringUtils;
import org.wm.utils.StringUtils;

import java.util.*;

/**
 * 角色 业务层处理
 * (已按照 Mybatis-Plus 混合模式进行改造)
 */
@RequiredArgsConstructor
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    private final SysRoleMenuMapper roleMenuMapper;
    private final SysUserRoleMapper userRoleMapper;
    private final SysRoleDeptMapper roleDeptMapper;

    @Override
    public IPage<SysRole> selectRoleList(Page<SysRole> page, SysRole role) {
        return baseMapper.selectRoleList(page, role);
    }

    @Override
    public List<SysRole> selectRolesByUserId(Long userId) {
        List<SysRole> userRoles = baseMapper.selectRolePermissionByUserId(userId);
        List<SysRole> roles = this.selectRoleAll();
        for (SysRole role : roles) {
            for (SysRole userRole : userRoles) {
                if (role.getRoleId().equals(userRole.getRoleId())) {
                    role.setFlag(true);
                    break;
                }
            }
        }
        return roles;
    }

    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = baseMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms) {
            if (perm != null && StringUtils.isNotEmpty(perm.getRoleKey())) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysRole> selectRoleAll() {
        return SpringUtils.getAopProxy(this).selectRoleList(ServiceUtils.queryAllPage(), new SysRole()).getRecords();
    }

    @Override
    public List<Long> selectRoleListByUserId(Long userId) {
        return baseMapper.selectRoleListByUserId(userId);
    }

    @Override
    public SysRole selectRoleById(Long roleId) {
        return this.getById(roleId);
    }

    @Override
    public String checkRoleNameUnique(SysRole role) {
        Long roleId = role.getRoleId() == null ? -1L : role.getRoleId();
        SysRole info = this.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleName, role.getRoleName()));
        if (info != null && !info.getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public String checkRoleKeyUnique(SysRole role) {
        Long roleId = role.getRoleId() == null ? -1L : role.getRoleId();
        SysRole info = this.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleKey, role.getRoleKey()));
        if (info != null && !info.getRoleId().equals(roleId)) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void checkRoleAllowed(SysRole role) {
        if (role.getRoleId() != null && role.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员角色");
        }
    }

    @Override
    public void checkRoleDataScope(Long roleId) {
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            SysRole role = new SysRole();
            role.setRoleId(roleId);
            IPage<SysRole> page = SpringUtils.getAopProxy(this).selectRoleList(ServiceUtils.queryAllPage(), role);
            if (page.getRecords().isEmpty()) {
                throw new ServiceException("没有权限访问角色数据！");
            }
        }
    }

    @Override
    public Long countUserRoleByRoleId(Long roleId) {
        return userRoleMapper.selectCount(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId));
    }

    @Override
    @Transactional
    public int insertRole(SysRole role) {
        // 使用 MP 的 save 方法
        this.save(role);
        return insertRoleMenu(role);
    }

    @Override
    @Transactional
    public boolean updateRole(SysRole role) {
        // updateById 本身就返回 boolean
        boolean success = this.updateById(role);
        if (success) {
            roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
            insertRoleMenu(role);
        }
        return success;
    }

    @Override
    public int updateRoleStatus(SysRole role) {
        // 使用 MP 的 updateById 方法，返回影响行数
        return this.updateById(role) ? 1 : 0;
    }

    @Override
    @Transactional
    public int authDataScope(SysRole role) {
        this.updateById(role);
        roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        return insertRoleDept(role);
    }

    @Override
    @Transactional
    public int deleteRoleById(Long roleId) {
        roleMenuMapper.deleteRoleMenuByRoleId(roleId);
        roleDeptMapper.deleteRoleDeptByRoleId(roleId);
        // 使用 MP 的 removeById 方法，返回影响行数
        return this.removeById(roleId) ? 1 : 0;
    }

    @Override
    @Transactional
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds) {
            checkRoleAllowed(new SysRole(roleId));
            SysRole role = this.getById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        roleMenuMapper.deleteRoleMenu(roleIds);
        roleDeptMapper.deleteRoleDept(roleIds);
        // 使用 MP 的 removeByIds 方法
        return this.removeByIds(Arrays.asList(roleIds)) ? roleIds.length : 0;
    }

    @Override
    public int deleteAuthUser(SysUserRole userRole) {
        return userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, userRole.getRoleId())
                .eq(SysUserRole::getUserId, userRole.getUserId()));
    }

    @Override
    public int deleteAuthUsers(Long roleId, Long[] userIds) {
        return userRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getRoleId, roleId)
                .in(SysUserRole::getUserId, Arrays.asList(userIds)));
    }

    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds) {
        List<SysUserRole> list = new ArrayList<>();
        for (Long userId : userIds) {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.isEmpty()) { return 1; }
        return userRoleMapper.batchUserRole(list);
    }

    // === 私有辅助方法 ===
    private int insertRoleMenu(SysRole role) {
        int rows = 1;
        if (role.getMenuIds() != null && role.getMenuIds().length > 0) {
            List<SysRoleMenu> list = new ArrayList<>();
            for (Long menuId : role.getMenuIds()) {
                SysRoleMenu rm = new SysRoleMenu();
                rm.setRoleId(role.getRoleId());
                rm.setMenuId(menuId);
                list.add(rm);
            }
            if (!list.isEmpty()) {
                rows = roleMenuMapper.batchRoleMenu(list);
            }
        }
        return rows;
    }

    private int insertRoleDept(SysRole role) {
        int rows = 1;
        if (role.getDeptIds() != null && role.getDeptIds().length > 0) {
            List<SysRoleDept> list = new ArrayList<>();
            for (Long deptId : role.getDeptIds()) {
                SysRoleDept rd = new SysRoleDept();
                rd.setRoleId(role.getRoleId());
                rd.setDeptId(deptId);
                list.add(rd);
            }
            if (!list.isEmpty()) {
                rows = roleDeptMapper.batchRoleDept(list);
            }
        }
        return rows;
    }
}